import React, { useEffect, useState } from 'react';
import { useAuth } from '../context/AuthContext';

export default function Home() {
  const { user } = useAuth();
  const [friends, setFriends] = useState([]);
  const [courses, setCourses] = useState([]);
  const [warnings, setWarnings] = useState([]);
  const [balance, setBalance] = useState(null);

  useEffect(() => {
    if (user) {
      if (user.is_admin) {
        fetch('/api/warning')
          .then(res => res.json())
          .then(data => setWarnings(data.data || []));
      } else {
        fetch(`/api/friend/${user.student_id}`)
          .then(res => res.json())
          .then(data => setFriends(data.data || []));
        fetch(`/api/enroll/${user.student_id}`)
          .then(res => res.json())
          .then(data => setCourses(data.data || []));
        fetch(`/api/balance/${user.student_id}`)
          .then(res => res.json())
          .then(data => setBalance(data.success ? data.balance : null));
      }
    }
  }, [user]);

  if (!user) return null;

  if (user.is_admin) {
    return (
      <div className="card" style={{ maxWidth: 1000, background: '#f5f7fa', boxShadow: '0 4px 24px rgba(0,0,0,0.08)' }}>
        <h2 style={{ textAlign: 'center', marginBottom: 24, color: '#1976d2' }}>欢迎，管理员 {user.name}（{user.student_id}）</h2>
        <div style={{ display: 'flex', gap: 32, marginBottom: 32 }}>
          <div style={{ flex: 1, background: '#e3f2fd', borderRadius: 10, padding: 24, minWidth: 260 }}>
            <b style={{ fontSize: 18, color: '#1976d2' }}>管理入口</b>
            <ul style={{ paddingLeft: 24, marginTop: 16, fontSize: 16 }}>
              <li>院系管理（可增删改查）</li>
              <li>课程管理（可增删改查）</li>
              <li>学生成绩录入</li>
              <li>转账预警管理</li>
            </ul>
          </div>
          <div style={{ flex: 2, background: '#fff3e0', borderRadius: 10, padding: 24, minWidth: 320 }}>
            <b style={{ fontSize: 18, color: '#f57c00' }}>所有转账预警记录</b>
            <table style={{ width: '100%', marginTop: 16, background: '#fff', borderRadius: 8, overflow: 'hidden' }}>
              <thead>
                <tr style={{ background: '#ffe0b2' }}>
                  <th>ID</th>
                  <th>学号</th>
                  <th>预警类型</th>
                  <th>触发时间</th>
                  <th>累计金额</th>
                </tr>
              </thead>
              <tbody>
                {warnings.length === 0 ? (
                  <tr><td colSpan={5} style={{ textAlign: 'center', color: '#888' }}>暂无预警</td></tr>
                ) : warnings
                  .sort((a, b) => new Date(b.trigger_time) - new Date(a.trigger_time))
                  .map(w => (
                  <tr key={w.warning_id}>
                    <td>{w.warning_id}</td>
                    <td>{w.student_id}</td>
                    <td>{w.rule_type === 1 ? '单笔超额' : '累计超额'}</td>
                    <td>{new Date(w.trigger_time).toLocaleString()}</td>
                    <td>{w.total_amount}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    );
  }

  // 普通学生首页
  return (
    <div className="card" style={{ maxWidth: 1000, background: '#f5f7fa', boxShadow: '0 4px 24px rgba(0,0,0,0.08)' }}>
      <h2 style={{ textAlign: 'center', marginBottom: 24, color: '#1976d2' }}>欢迎，{user.name}（{user.student_id}）</h2>
      <div style={{ display: 'flex', gap: 32, flexWrap: 'wrap' }}>
        <div style={{ flex: 1, minWidth: 260, background: '#e3f2fd', borderRadius: 10, padding: 24 }}>
          <h3 style={{ color: '#1976d2' }}>我的信息</h3>
          <div style={{ lineHeight: 2, fontSize: 16 }}>
            <div><b>姓名：</b>{user.name}</div>
            <div><b>学号：</b>{user.student_id}</div>
            <div><b>出生日期：</b>{user.birth_date}</div>
            <div><b>身份证号：</b>{user.id_card}</div>
            <div><b>地址：</b>{user.address}</div>
            <div><b>余额：</b>{balance !== null ? <span style={{ color: '#1976d2', fontWeight: 600 }}>{balance} 元</span> : '加载中...'}</div>
          </div>
        </div>
        <div style={{ flex: 1, minWidth: 260, background: '#fff3e0', borderRadius: 10, padding: 24 }}>
          <h3 style={{ color: '#f57c00' }}>我的好友</h3>
          <ul style={{ paddingLeft: 18, fontSize: 16 }}>
            {friends.length === 0 && <li>暂无好友</li>}
            {friends.map(f => (
              <li key={f.friend_id}>{f.name}（{f.friend_id}）<br /><span style={{ fontSize: 12, color: '#888' }}>成为好友时间：{new Date(f.since_time).toLocaleString()}</span></li>
            ))}
          </ul>
        </div>
        <div style={{ flex: 1, minWidth: 260, background: '#e8f5e9', borderRadius: 10, padding: 24 }}>
          <h3 style={{ color: '#388e3c' }}>我的课程</h3>
          <ul style={{ paddingLeft: 18, fontSize: 16 }}>
            {courses.length === 0 && <li>暂无选课</li>}
            {courses.map(c => (
              <li key={c.course_id}>{c.course_name}（{c.course_id}）<br /><span style={{ fontSize: 12, color: '#888' }}>成绩：{c.grade !== null ? c.grade : '未录入'}</span></li>
            ))}
          </ul>
        </div>
      </div>
    </div>
  );
} 